package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.admin.mapper.AdUserMapper;
import com.heima.admin.service.AdUserService;
import com.heima.common.constants.admin.AdminConstants;
import com.heima.model.admin.dtos.AdUserDto;
import com.heima.model.admin.dtos.AdUserRegisterDto;
import com.heima.model.admin.pojos.AdUser;
import com.heima.model.admin.vos.AdUserVO;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.AppJwtUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class AdUserServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements AdUserService {


    @Override
    public ResponseResult login(AdUserDto dto) {

        //1.检查数据
        if (dto==null || StringUtils.isEmpty(dto.getName())||StringUtils.isEmpty(dto.getPassword())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "数据错误，请召唤前端工作人员");
        }

        //2.根据用户名查询用户信息

        String name = dto.getName();

        LambdaQueryWrapper<AdUser> queryWrapper = Wrappers.<AdUser>lambdaQuery();

        queryWrapper.eq(AdUser::getName, name);

        AdUser user = getOne(queryWrapper);

        if (user==null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST, "用户不存在");
        }
        //3.查询密码是否正确，以及是否激活

        String password = user.getPassword();
        String salt = user.getSalt();

        String newPassword = DigestUtils.md5DigestAsHex((dto.getPassword() + salt).getBytes());
        if (!newPassword.equals(password)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "用户名或密码错误");
        }

        if (user.getStatus() != 9) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "用户未激活，请先激活");
        }


        //4.更新用户信息

        user.setLoginTime(new Date());
        updateById(user);
        String token = AppJwtUtil.getToken(user.getId().longValue());

        AdUserVO userVO = new AdUserVO();

        BeanUtils.copyProperties(user, userVO);

        //5.返回结果，登录成功

        Map map = new HashMap();

        map.put("token", token);

        map.put("user", userVO);

        return ResponseResult.okResult(map);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult register(AdUserRegisterDto dto) {

        //1.检测数据

        if (dto==null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "数据填写不正确");
        }
        //2.查询是否已经注册

        AdUser user = getOne(Wrappers.<AdUser>lambdaQuery().eq(AdUser::getName, dto.getName()));

        if (user!=null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "用户名已存在");
        }
        //3.加密密码
        String password = DigestUtils.md5DigestAsHex((dto.getPassword() + dto.getSalt()).getBytes());

        AdUser adUser = new AdUser();
        //4.注册

        BeanUtils.copyProperties(dto, adUser);

        adUser.setPassword(password);

       adUser.setCreatedTime(new Date());

        adUser.setStatus(9);

        save(adUser);

        //5.发送激活邮件（懒得写了 先手激活一波）

        //6.返回数据

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
